package com.todod.base.framework.common.util.office;
import org.apache.pdfbox.pdmodel.PDDocument;
import org.apache.pdfbox.pdmodel.PDPage;
import org.apache.pdfbox.pdmodel.PDPageContentStream;
import org.apache.pdfbox.pdmodel.graphics.image.PDImageXObject;
import org.apache.pdfbox.rendering.ImageType;
import org.apache.pdfbox.rendering.PDFRenderer;

import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.*;

public class PdfUtils {

    /**
     * 添加图片作为印章
     * @param pdfPath pdf文件路径
     * @param imagePath 签字图片路径
     * @param signPageIndex 签字页数（从0开始）
     * @param width     签字图片宽度
     * @param height    签字图片高度
     * @param x         签字位置x轴（从左到右加大）
     * @param y         签字位置y轴（从下到上加大）
     * @param outputFilePath 输出文件路径
     * @param outputFileName 输出文件名称
     */
    public static void addImageAsStamp(String pdfPath, String imagePath,int signPageIndex,int width, int height, float x, float y,String outputFilePath,String outputFileName){
        try (PDDocument document = PDDocument.load(new File(pdfPath))) {
            PDPage page = document.getPage(signPageIndex);
            PDImageXObject pdImage = PDImageXObject.createFromFile(imagePath, document);

            PDPageContentStream contentStream = new PDPageContentStream(document, page, PDPageContentStream.AppendMode.APPEND, true, true);
            contentStream.drawImage(pdImage, x, y, width,height); // pdImage.getWidth(), pdImage.getHeight());
            contentStream.close();

            document.save(new File(outputFilePath+outputFileName+".pdf"));
        } catch (IOException e){
            System.out.println("Error adding image as stamp: " + e.getMessage());
        }
        }


    public static byte[] convertPdfToImage(File pdfFile, int pageNumber, String imageFormat) {
        try (PDDocument document = PDDocument.load(pdfFile)) {
            PDFRenderer pdfRenderer = new PDFRenderer(document);
            BufferedImage bufferedImage = pdfRenderer.renderImageWithDPI(pageNumber, 300, ImageType.RGB);

            ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
            ImageIO.write(bufferedImage, imageFormat, outputStream);
            return outputStream.toByteArray();
        } catch (IOException e){
            System.out.println("Error converting PDF to image: " + e.getMessage());
            return null;
        }
    }

    /**
     * 读取ftp上的pdf文件 并转成图片
     * @param resp
     * @param path
     * @throws Exception
     */

    public static void readPdfFileImg(String path){
        try {
            // 获取ftp的文件字节流
            InputStream is = new FileInputStream(path);
            // pdf转图片
            PDDocument doc = PDDocument.load(is);
            PDFRenderer renderer = new PDFRenderer(doc);
            int pageCount = doc.getNumberOfPages();
            for (int i = 0; i < pageCount; i++) {
                ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
                // dpi，图片像素点，dpi越高图片体积越大，216很清晰，105体积稳定
                BufferedImage image = renderer.renderImageWithDPI(i, 216);
                // 格式为JPG
                ImageIO.write(image, "png", outputStream);
            }
            String filename = path.substring(path.lastIndexOf("/") + 1).replaceAll(".pdf", ".png");
        }catch (Exception e){
            e.printStackTrace();
        }
    }

    /**
     * pdf转图片
     * @param pdfFile pdf文件
     * @param imageFormat 图片后缀
     * @return
     */
    public static byte[] convertPdfToImageAll(File pdfFile, String imageFormat,String path, String fileName,String suffix) {
        try (PDDocument document = PDDocument.load(pdfFile)) {
            PDFRenderer pdfRenderer = new PDFRenderer(document);
            int pageCount = document.getNumberOfPages();

            for (int i = 0; i < pageCount; i++) {
                BufferedImage bufferedImage = pdfRenderer.renderImageWithDPI(i, 300, ImageType.RGB);

                ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
                ImageIO.write(bufferedImage, imageFormat, outputStream);
                FileToBase64.convertBytesToImage(outputStream.toByteArray(), path+fileName+"_"+i+suffix);
            }


            return null;//outputStream.toByteArray();
        } catch (IOException e){
            System.out.println("Error converting PDF to image: " + e.getMessage());
            return null;
        }
    }

    /**
     * pdf转图片
     * @param pdfFile pdf文件
     * @param imageFormat 图片后缀
     * @return
     */
    public static byte[] convertPdfToImageAlone(File pdfFile, String imageFormat,String path, String fileName,String suffix,int i) {
        try (PDDocument document = PDDocument.load(pdfFile)) {
            PDFRenderer pdfRenderer = new PDFRenderer(document);

            BufferedImage bufferedImage = pdfRenderer.renderImageWithDPI(i, 300, ImageType.RGB);
            ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
            ImageIO.write(bufferedImage, imageFormat, outputStream);
            FileToBase64.convertBytesToImage(outputStream.toByteArray(), path+fileName+"_"+i+suffix);

            return null;//outputStream.toByteArray();
        } catch (IOException e){
            System.out.println("Error converting PDF to image: " + e.getMessage());
            return null;
        }
    }

    public static void main(String[] args) {
//            addImageAsStamp("/mydeploy/file/generate/contract/pdf/NH202408240000000045.pdf.pdf", "/mydeploy/file/generate/contract/stamp.png", 100, 200); // 100,200是图章的位置坐标
    }
}